package cn.edu.scau.cmi.maintain.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cn.edu.scau.cmi.ema.domain.Address;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.util.CmiHibernateProxyUtil;
import cn.edu.scau.cmi.ema.util.ExcelUtil;
import cn.edu.scau.cmi.ema.util.SegmenterUtil;
import cn.edu.scau.cmi.front.controller.FrontCmiEmaController;
import cn.edu.scau.cmi.front.domain.FuzzyAddress;
import cn.edu.scau.cmi.front.service.FuzzyAddressService;

/**
 * 原来是在测试源文件夹中的方法，简化起见，放到
 * 
 */

@Controller

//@PropertySource(value = { "classpath:food2type.properties" })

public class MaintainAddressController extends FrontCmiEmaController {
	
	@Autowired
	protected FuzzyAddressService fuzzyAddressService;
	

	
	private String testWorkbook = "E:\\Workspace\\git\\ema\\ema\\项目文档\\静态适配数据\\（5）静态适配数据-张星联地址自动适配测试.xlsx";
	private String testOutputWorkbook = "E:\\Workspace\\git\\ema\\ema\\项目文档\\静态适配数据\\（5）静态适配数据-张星联地址自动适配测试-输出文件.xlsx";
	
	

//	从电子表格中列出所有的需要匹配的地址
	@RequestMapping("/listRows4MatchedAddresses")
	public ModelAndView listRows4MatchedAddresses(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		List<FuzzyAddress> fuzzyAddressList = new ArrayList<FuzzyAddress>();
//			page = new CmiPagination(eventService.countEvents());
//		}
		
		Workbook workbook = ExcelUtil.getWorkbook(testWorkbook);
		Sheet sheet = workbook.getSheetAt(0);
		int lastRowNum = sheet.getLastRowNum();
		
//		每一行中的地址字符串封装为一个FuzzyAddress对象
//		从第二行开始是数据，每次处理100条数据。
		for(int rowNum=2, quantity =0; rowNum<lastRowNum && quantity< 100;rowNum++, quantity++) {
			
			int isDealedColumn = 4;//是否已经处理的列，0表示没有处理，1表示已经处理了。
			Row eventRow = sheet.getRow(rowNum);
			Cell isDealedCell = eventRow.getCell(isDealedColumn);
			String isDealed = ExcelUtil.getCellValue(isDealedCell);
			if(!isDealed.equals("0")) {
				continue;
			}
			
			FuzzyAddress fuzzyAddress = new FuzzyAddress();
			int fuzzyAddressColumn = 3;//原始的发现地址
			
			Cell fuzzyAddressCell = eventRow.getCell(fuzzyAddressColumn);
			String fuzzyAddressName = ExcelUtil.getCellValue(fuzzyAddressCell);
			
//			所有的分词
			Set<String> segments = SegmenterUtil.getSegmentByIndex(fuzzyAddressName);
			
			//有效的分词
			Set<String> validSegments = new HashSet<String>();
			
//			去除明显不合理的分词的数据
			for(String segment: segments) {
				if(!   ((segment.matches("[0-9]+" ) || segment.length() <2))  ) {
					validSegments.add(segment);
				}
			}
			
			fuzzyAddress.setRowNumber(rowNum);
			fuzzyAddress.setName(fuzzyAddressName);
			fuzzyAddress.setSegments(validSegments);
			
			fuzzyAddressList.add(fuzzyAddress);
		}
	
//		mav.addObject("page", page);
		mav.addObject("fuzzyAddressList", fuzzyAddressList);
		mav.setViewName("maintance/listRows4MatchedAddresses.jsp");
		return mav;
	}
	
	
//	获取单个的地址的匹配情况，返回json数据，请求数据是地址的分词字符串，中间使用空格连接
	@RequestMapping(value = "/restFuzzyMatchAddress/{addressesString}", method = RequestMethod.GET)
	@ResponseBody
	
	public Object fuzzyMatchAddress(HttpServletRequest request, @PathVariable String addressesString) {
		
		String[] addressesStringList = addressesString.split(" ");
		Set<String> addressesStringSet = new HashSet<String>();
		for(int i=0;i<addressesStringList.length;i++) {
			addressesStringSet.add(addressesStringList[i]);
		}
		
		List<Address> fuzzyAddressList = fuzzyAddressService.fuzzyAddresses(addressesStringSet);
		CmiPsonService cmiPsonService = new CmiPsonService();
		CmiPagination cmiPagination = new CmiPagination();
		return JSONObject.parse(cmiPsonService.toPsonString(fuzzyAddressList, 2, cmiPagination));
	}
	
//	<a herf="/restSaveFuzzyAddress/826771">张沟村：亚洲中国湖北省省直辖县级行政区划仙桃市张沟镇张沟村</a>
//	将页面中选中的结果保存到电子表格中
//	rowNumber: 电子表格中的行号；addressId：本地地址的id； baiduMatchAddressName：百度匹配的地址 
	
	@RequestMapping(value = "/restSaveMatchAddressIntoExcel/{rowNumber}/{addressId}/{baiduMatchAddressName}", method = RequestMethod.GET)
	@ResponseBody
	public Object restSaveFuzzyAddress(HttpServletRequest request, @PathVariable Integer rowNumber, @PathVariable String addressId, @PathVariable String baiduMatchAddressName) throws Throwable {
		String detailAddressName = "";
		if(!addressId.equals("null")) {
			detailAddressName = addressDAO.findAddressById(Integer.parseInt(addressId)).getDescription();
		}
		
		int isDealedColumn = 4;//第4列表示是否已经处理
		int addressColumn = 6;//第六列是发现地址的本地匹配
		int baiduMatchAddressColumn = 7;//第7列是百度匹配的地址主体
		
		Map<Integer, String> valueMap = new HashMap<Integer, String>();
		valueMap.put(isDealedColumn, "1");
		valueMap.put(addressColumn, detailAddressName);
		valueMap.put(baiduMatchAddressColumn, baiduMatchAddressName);
		
		
		Workbook workbook = ExcelUtil.getWorkbook(testWorkbook);
		Sheet sheet = workbook.getSheetAt(0);
		Row row = sheet.getRow(rowNumber);
		
		ExcelUtil.saveRow(detailAddressName, row, valueMap );
		
		//saveMatchAddressIntoExcel(Integer.parseInt(rowNumber), detailAddressName, addressColumn, baiduMatchAddressName, baiduMatchAddressColumn);
//		TODO　需要修改：2020年12月23号
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("result", "SUCCESS");
		
		return jsonObject;
	}
	
//	2020年12月24号，这个方法不要了
	/*
	 * public void saveMatchAddressIntoExcel(int rowNumber, String
	 * detailAddressName, int addressColumn, String baiduMatchAddressName, int
	 * baiduMatchAddressColumn) throws Throwable {
	 * 
	 * Workbook workbook = ExcelUtil.getWorkbook(testWorkbook); Sheet sheet =
	 * workbook.getSheetAt(0); Row row = sheet.getRow(rowNumber);
	 * 
	 * Cell isDealedsCell = row.getCell(4); isDealedsCell.setCellValue("1");
	 * 
	 * Cell localMatchAddressCell = row.getCell(addressColumn);
	 * localMatchAddressCell.setCellValue(detailAddressName);
	 * 
	 * Cell baiduMatchAddressCell = row.getCell(baiduMatchAddressColumn);
	 * baiduMatchAddressCell.setCellValue(baiduMatchAddressName);
	 * 
	 * 
	 * FileOutputStream ops = new FileOutputStream(testWorkbook);
	 * workbook.write(ops); ops.flush(); ops.close(); }
	 */


	//	获取模糊匹配的地址
	@RequestMapping("/matchAddress")
	public ModelAndView fuzzyAddresses(HttpServletRequest request) {
		
		ModelAndView mav = new ModelAndView();
		
		Workbook workbook = ExcelUtil.getWorkbook("E:\\Workspace\\git\\ema\\ema\\项目文档\\静态适配数据\\（5）静态适配数据-张星联-测试35条记录.xlsx");
		Sheet sheet = workbook.getSheetAt(0);
		int lastRowNum = sheet.getLastRowNum();
		
		for(int roeNum=0; roeNum<lastRowNum;roeNum++) {
			Row row = sheet.getRow(roeNum);
			int cellnum = 3;//发现地址
			Cell cell = row.getCell(cellnum);
			String cellValue = ExcelUtil.getCellValue(cell);
			
			Set<String> validSegments = new HashSet<String>();
			
			Set<String> segments = SegmenterUtil.getSegmentByIndex(cellValue);
			
//			去除明显不合理的分词的数据
			for(String segment: segments) {
				if(!   ((segment.matches("[0-9]+" ) || segment.length() <2))  ) {
					validSegments.add(segment);
				}
			}
			System.out.println("！！！！！！！！！！！！！电子表格中地址分词后：" + validSegments);
			List<Address> fuzzyAddressList = fuzzyAddressService.fuzzyAddresses(validSegments);
//			System.out.println("！！！！！！！！！！！！！模糊匹配后的有效地址是：" + fuzzyAddressList);
			
			System.out.println("！！！！！！！！！！！！！从电子表格中读取的需要模糊匹配的地址名：" + cellValue);
			
			for(int fuzzyAddressNum=0; fuzzyAddressNum<fuzzyAddressList.size() && fuzzyAddressNum<10;fuzzyAddressNum++) {
//			for(Address address: fuzzyAddressList) {
				System.out.println("      从数据库中模糊匹配的地址名：" + fuzzyAddressList.get(fuzzyAddressNum).getName() + "   地址的全称是：   " + fuzzyAddressList.get(fuzzyAddressNum).getDescription());
			}
			System.out.println();
//			System.out.print("发现地址是：" + cellValue);
//			System.out.println("，分词后去除不合理的分词的结果是：" + validSegments);
		}
	
		
		mav.setViewName("front/frontTrend.jsp");
		return mav;
	}

	@SuppressWarnings("unused")
	@Transactional(timeout=300000000)//解决懒加载问题
	@RequestMapping(value = "/updateAddressDescription", method = RequestMethod.GET)
	@ResponseBody
	public void updateAddressDescription () throws Exception {
		
//		Address addr  = CmiHibernateProxyUtil.deproxy(addressDAO.findAddressById(9));
//		System.out.println(addr.getParent().getName());
//		
		Integer level = 5;
		Set<Address> proxyAddresss = addressDAO.findAddressByLevel(level );
		for(Address proxyAddress: proxyAddresss) {
			Address address = CmiHibernateProxyUtil.deproxy(addressDAO.findAddressById(proxyAddress.getId()));
			System.out.print("地址  " + address.getName());
			System.out.println("的上级地址是：" + address.getParent().getName());
			address.setDescription(address.getParent().getDescription() + address.getName());
			System.out.println(address.getDescription());
			System.out.println();
			address = addressService.saveAddress(address);
			
		}
	}
	
	@SuppressWarnings("unused")
	@Transactional(timeout=300000000)//解决懒加载问题
	@RequestMapping(value = "/fuzzyAddresses", method = RequestMethod.GET)
	@ResponseBody
	public void fuzzyAddresses () throws Exception {
		
		Workbook workbook = ExcelUtil.getWorkbook("E:\\Workspace\\git\\ema\\ema\\项目文档\\静态适配数据\\（5）静态适配数据-张星联-测试35条记录.xlsx");
		Sheet sheet = workbook.getSheetAt(0);
		int lastRowNum = sheet.getLastRowNum();
		
		for(int roeNum=0; roeNum<lastRowNum;roeNum++) {
			Row row = sheet.getRow(roeNum);
			int cellnum = 3;//发现地址
			Cell cell = row.getCell(cellnum);
			String cellValue = ExcelUtil.getCellValue(cell);
			
			Set<String> validSegments = new HashSet<String>();
			
			Set<String> segments = SegmenterUtil.getSegmentByIndex(cellValue);
			
//			去除明显不合理的分词的数据
			for(String segment: segments) {
				if(!   ((segment.matches("[0-9]+" ) || segment.length() <2))  ) {
					validSegments.add(segment);
				}
			}
			System.out.println("！！！！！！！！！！！！！电子表格中地址分词后：" + validSegments);
			List<Address> fuzzyAddressList = fuzzyAddressService.fuzzyAddresses(validSegments);
//			System.out.println("！！！！！！！！！！！！！模糊匹配后的有效地址是：" + fuzzyAddressList);
			
			System.out.println("！！！！！！！！！！！！！从电子表格中读取的需要模糊匹配的地址名：" + cellValue);
			
			for(int fuzzyAddressNum=0; fuzzyAddressNum<fuzzyAddressList.size() && fuzzyAddressNum<10;fuzzyAddressNum++) {
//			for(Address address: fuzzyAddressList) {
				System.out.println("      从数据库中模糊匹配的地址名：" + fuzzyAddressList.get(fuzzyAddressNum).getName() + "   地址的全称是：   " + fuzzyAddressList.get(fuzzyAddressNum).getDescription());
			}
			System.out.println();
			System.out.println();
			System.out.println();
//			System.out.print("发现地址是：" + cellValue);
//			System.out.println("，分词后去除不合理的分词的结果是：" + validSegments);
		}
		
		
		
		
		
//		List<Address> fuzzyAddressList = fuzzyAddressService.fuzzyAddresses("福建省/南平/武夷山市/度假区/曼陀岩/（/中国/旅游/商贸城/）");
//		List<Address> fuzzyAddressList = fuzzyAddressService.fuzzyAddresses("福建省/仙桃市");
//		System.out.println(fuzzyAddressList);
	}
}